package com.example.tnorder.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
//实现UserDetailsService 该接口完成自定义认证过程
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据库
        LambdaQueryWrapper<com.yc.pojo.User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(com.yc.pojo.User::getPhone,username);
        com.yc.pojo.User user = userService.getOne(queryWrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<GrantedAuthority> auths=
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        if (user.getRole()==2){
            auths.add(()-> "admin");
        }
        //返回的自定义用户对象的参数：第一个用户名，第二个密码，第三个权限
        return new User(username
                ,new BCryptPasswordEncoder().encode(user.getPassword())
                ,auths
        );
    }
}
